﻿var ProfileSetting = function () {
    // 页面全局
    toastr.options = {
        "closeButton": false,
        "debug": false,
        "positionClass": "toast-top-center",
        "onclick": null,
        "showDuration": "500",
        "hideDuration": "500",
        "timeOut": "2000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    };

    var initUpdateAvatar = function () {
        var avatar = $("#fileAvatar");
        var btnUpload = $("#btnUpload");
        var btnCancelUpload = $("#btnCancelUpload");
        var jQueryForm = $("#avatarForm");
        var fileuoloadData = null;

        avatar.fileupload({
            dataType: "json",
            url: jQueryForm.attr("action"),
            autoUpload: false,
            maxFileSize: 1000000,
            acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
            add: function (e, data) {
                fileuoloadData = data;
            },
            done: function (e, data) {
                btnUpload.message(data.result);
                btnUpload.init();
            },
            fail: function (e, data) {
                toastr["error"]("您没有权限或是程序碰到问题没有正确执行！", "更新用户头像");
                btnUpload.init();
            }
        });

        // 大图预览
        var upPreviewLarge = avatar.uploadImagePreview({
            previewContainerID: 'avatarLargePreview',
            imgWidth: 125
        });
        // 小图预览
        var upPreviewSmall = avatar.uploadImagePreview({
            previewContainerID: 'avatarSmallPreview',
            imgWidth: 30
        });

        btnCancelUpload.bind("click", function () {
            fileuoloadData = null;
            upPreviewLarge.reset();
            upPreviewSmall.reset();
        });
        btnUpload.init = function () {
            this.empty().html("更新头像");
            this.removeAttr("disabled");
        }
        btnUpload.message = function (response) {
            if (response.Result) {
                var picUrl = response.Data.PicUrl;
                var uid = response.Data.UID;
                var smallPicUrl = picUrl + "small.png?" + Math.random();
                $("#profile_userpic > img").attr("src", picUrl + "large.png?" + Math.random());
                $("#tr_" + uid + " img[data-field='avatar']").attr("src", smallPicUrl);
                $("#user_avatar").attr("src", smallPicUrl);
                toastr["success"](response.Message, "更新用户头像");
            } else {
                toastr["error"](response.Message, "更新用户头像");
            }
        }
        btnUpload.bind("click", function () {
            if (fileuoloadData) {
                btnUpload.empty().append('<i class="fa fa-spinner fa-spin"></i> 正在保存');
                btnUpload.attr("disabled", "disabled");
                fileuoloadData.submit();
            } else {
                toastr["warning"]("并未选择要上传的照片！", "更新用户头像");
            }
        });
    };

    var initUpdateProfileInfo = function () {
        $("#updateForm")
        .AjaxForm({
            submitButton: {
                selector: "#btnUpdateUser",
                loadingText: "正在更新"
            },
            resetButton: {
                selector: "#btnUpdateUserCancel"
            },
            alertTitle: "更新个人信息",
            notCompletedResetForm: false,
            success: function (response, title) {
                var args = [];
                args.push(response.Message);
                if (title) args.push(title);

                if (response.Result) {
                    var Fields = response.Data;
                    var fullName = Fields.CNName ? Fields.FirstName + Fields.LastName : Fields.LastName + ' ' + Fields.FirstName;

                    $("#profile_email").html(Fields.Email);
                    if (Fields.Email) $("#profile_email").attr("href", "mailto:" + Fields.Email);
                    $("#profile_phone").html(Fields.Phone);
                    $("#profile_qq").html(Fields.QQ);
                    $("#profile_fullname").html("关于 " + fullName);
                    $("#profile_primary_fullname").html(fullName);
                    $("#profile_memo").html(Fields.Memo ? Fields.Memo : "什么信息都没有留下");

                    toastr["success"].apply(this, args);
                } else {
                    toastr["error"].apply(this, args);
                }
            }
        })
        .validate({
            onsubmit: false,
            rules: {
                firstname: {
                    required: true,
                    maxlength: 15
                },
                lastname: {
                    required: true,
                    maxlength: 15
                },
                email: {
                    required: true,
                    email: true,
                    maxlength: 100
                },
                phone: {
                    maxlength: 11
                },
                qq: {
                    maxlength: 11
                },
                memo: {
                    maxlength: 200
                }
            },
            messages: {
                firstname: {
                    required: "您的姓氏需要填写",
                    maxlength: "字数不能超过15个"
                },
                lastname: {
                    required: "您的名字需要填写",
                    maxlength: "字数不能超过15个"
                },
                email: {
                    required: "Email必须要填写哦，可以用来找回密码的",
                    email: "邮箱格式不正确",
                    maxlength: "字符数不能超过100个"
                },
                phone: {
                    maxlength: "字符数不能超过11个"
                },
                qq: {
                    maxlength: "字符数不能超过11个"
                },
                memo: {
                    maxlength: "字符数不能超过200个"
                }
            },
            errorPlacement: function (error, element) {
                error.removeClass().addClass("text-danger ml-20");
                var _container = element.prev();
                _container.empty();
                error.appendTo(_container);
                element.parent().removeClass("has-success").addClass("has-error");
            },
            success: function (label, element) {
                label.empty().append('<i class="fa fa-check"></i>');
                label.removeClass().addClass("text-success ml-20");
                $(element).parent().removeClass("has-error").addClass("has-success");
            }
        });
    };

    var initProfilePassword = function () {
        $("#updatePasswordForm")
        .AjaxForm({
            submitButton: {
                selector: "#btnUpdatePWD",
                loadingText: "正在更新"
            },
            resetButton: {
                selector: "#btnCancelUpdatePWD"
            },
            alertTitle: "更新个人密码"
        })
        .validate({
            onsubmit: false,
            rules: {
                currpassword: {
                    required: true
                },
                newpassword: {
                    required: true,
                    minlength: 6
                },
                confirmpassword: {
                    required: true,
                    equalTo: "#newpassword"
                }
            },
            messages: {
                currpassword: {
                    required: "未提供初始密码"
                },
                newpassword: {
                    required: "必须提供新的密码",
                    minlength: "密码至少要6位"
                },
                confirmpassword: {
                    required: "请确认您输入的密码",
                    equalTo: "您输入的密码不一致"
                }
            },
            errorPlacement: function (error, element) {
                error.removeClass().addClass("text-danger ml-20");
                var _container = element.prev();
                _container.empty();
                error.appendTo(_container);
                element.parent().removeClass("has-success").addClass("has-error");
            },
            success: function (label, element) {
                label.empty().append('<i class="fa fa-check"></i>');
                label.removeClass().addClass("text-success ml-20");
                $(element).parent().removeClass("has-error").addClass("has-success");
            }
        });
    };

    return {
        init: function () {
            Metronic.initComponents();
            initUpdateAvatar();
            initUpdateProfileInfo();
            initProfilePassword();
        }
    };
} ();